<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户名" prop="busOtherCpyName">
        <el-input
          v-model="queryParams.busOtherCpyName"
          placeholder="请输入客户名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发票编号" prop="invoiceNumber">
        <el-input
          v-model="queryParams.invoiceNumber"
          placeholder="请输入发票编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable style="width:150px">
          <el-option
            v-for="dict in invoice_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['invoice:invoice:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['invoice:invoice:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['invoice:invoice:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="invoiceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="业务来源" align="center" prop="salesOrderId" />
      <el-table-column label="开票人" align="center" prop="invoiceByName" />
      <el-table-column label="收款人" align="center" prop="cashByName" />
      <el-table-column label="购方银行账号" align="center" prop="customBankNo" />
      <el-table-column label="购方开户银行名称" align="center" prop="customBankName" />
      <el-table-column label="客户名" align="center" prop="busOtherCpyName" />
      <el-table-column label="发票类型" align="center" prop="invoiceType">
        <template #default="scope">
          <dict-tag :options="invoice_type" :value="scope.row.invoiceType"/>
        </template>
      </el-table-column>
      <el-table-column label="发票编号" align="center" prop="invoiceNumber" />
      <el-table-column label="发票金额" align="center" prop="amount" />

      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="invoice_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['invoice:invoice:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['invoice:invoice:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改发票对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="invoiceRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="销售订单" prop="salesOrderId">
          <el-input v-model="form.salesOrderId" placeholder="请输入联销售订单" />
        </el-form-item>
        <el-form-item label="开票人" prop="invoiceByName">
          <el-input v-model="form.invoiceByName" placeholder="请输入开票人" />
        </el-form-item>
        <el-form-item label="收款人" prop="cashByName">
          <el-input v-model="form.cashByName" placeholder="请输入收款人" />
        </el-form-item>
        <el-form-item label="购方银行账号" prop="customBankNo">
          <el-input v-model="form.customBankNo" placeholder="请输入购方银行账号" />
        </el-form-item>
        <el-form-item label="购方开户银行" prop="customBankName">
          <el-input v-model="form.customBankName" placeholder="请输入购方开户银行名称" />
        </el-form-item>
        <el-form-item label="客户名" prop="busOtherCpyName">
          <el-input v-model="form.busOtherCpyName" placeholder="请输入客户名" />
        </el-form-item>
        <el-form-item label="发票编号" prop="invoiceNumber">
          <el-input v-model="form.invoiceNumber" placeholder="请输入发票编号" />
        </el-form-item>
        <el-form-item label="发票金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入发票金额" />
        </el-form-item>
        <el-form-item label="发票类型" prop="invoiceType">
          <el-select v-model="form.invoiceType" placeholder="请选择发票类型">
            <el-option
              v-for="dict in invoice_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createdTime">
          <el-date-picker clearable
            v-model="form.createdTime"
            type="datetime"
            value-format="YYYY-MM-DD hh:mm:ss"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="附件" prop="annex">
          <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeUpload"
        >
          <img v-if="otherUrl" :src="otherUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Invoice">
import { listInvoice, getInvoice, delInvoice, addInvoice, updateInvoice } from "@/api/finance/invoice";
import {uploadOther} from "@/api/finance/billing";
import useUserStore from '@/store/modules/user'
const { proxy } = getCurrentInstance();
const { invoice_status, invoice_type } = proxy.useDict('invoice_status', 'invoice_type');
const invoiceList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

//附件图片地址
const otherUrl = ref()

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    salesOrderId: null,
    invoiceByName: null,
    cashByName: null,
    customBankNo: null,
    customBankName: null,
    busOtherCpyName: null,
    invoiceNumber: null,
    amount: null,
    invoiceType: null,
    createdTime: null,
    createBy: null,
    updatedTime: null,
    annex: null
  },
  rules: {
    salesOrderId: [
      { required: true, message: "关联销售订单表不能为空", trigger: "blur" }
    ],
    invoiceByName: [
      { required: true, message: "开票人不能为空", trigger: "blur" }
    ],
    cashByName: [
      { required: true, message: "收款人不能为空", trigger: "blur" }
    ],
    customBankNo: [
      { required: true, message: "购方银行账号不能为空", trigger: "blur" }
    ],
    customBankName: [
      { required: true, message: "购方开户银行名称不能为空", trigger: "blur" }
    ],
    busOtherCpyName: [
      { required: true, message: "客户名不能为空", trigger: "blur" }
    ],
    invoiceNumber: [
      { required: true, message: "发票编号不能为空", trigger: "blur" }
    ],
    amount: [
      { required: true, message: "发票金额不能为空", trigger: "blur" }
    ],
    invoiceType: [
      { required: true, message: "发票类型   1 普通发票  2专用发票不能为空", trigger: "change" }
    ],
    createdTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
    createBy: [
      { required: true, message: "创建者不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询发票列表 */
function getList() {
  loading.value = true;
  listInvoice(queryParams.value).then(response => {
    invoiceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function handleAvatarSuccess( response,uploadFile){
  console.log(uploadFile);
  
  // imageUrl.value = URL.createObjectURL(!uploadFile.raw)
}


/** 上传图片 */
function beforeUpload(file){
  let formData = new FormData()
  formData.append('other',file)
  uploadOther(formData).then(resp => {
    form.value.other = resp.msg
  })
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    salesOrderId: null,
    invoiceByName: null,
    cashByName: null,
    customBankNo: null,
    customBankName: null,
    busOtherCpyName: null,
    invoiceNumber: null,
    amount: null,
    invoiceType: null,
    createdTime: null,
    createBy: null,
    updatedTime: null,
    annex: null
  };
  proxy.resetForm("invoiceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加发票";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getInvoice(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改发票";
  });
}

/** 提交按钮 */
function submitForm() {
  form.value.createBy = useUserStore().id
  proxy.$refs["invoiceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateInvoice(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addInvoice(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除发票编号为"' + _ids + '"的数据项？').then(function() {
    return delInvoice(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('invoice/invoice/export', {
    ...queryParams.value
  }, `invoice_${new Date().getTime()}.xlsx`)
}

getList();
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>


<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width:120px;
  height: 120px;
  text-align: center;
}
</style>
